package com.zjc.netty.client;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoop;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;

import java.net.InetSocketAddress;
import java.util.concurrent.TimeUnit;

public class NettyClient {
    NioEventLoopGroup group = new NioEventLoopGroup();
    InetSocketAddress inetSocketAddress;

    int count;

    public NettyClient(InetSocketAddress inetSocketAddress) {
        this.inetSocketAddress = inetSocketAddress;
    }


    public void start() {
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(group)
                .channel(NioSocketChannel.class)
                .remoteAddress(inetSocketAddress)
                .handler(new CustomChannelInitializer(null));

        try {
            ChannelFuture f = bootstrap.connect().addListener((ChannelFuture futureListener) -> {
                final EventLoop eventLoop = futureListener.channel().eventLoop();
                if (!futureListener.isSuccess()) {
                    if (count < 3) {
                        System.err.println("客户端已启动，与服务端建立连接失败,60s之后尝试重连!");
                        eventLoop.schedule(() -> start(), 60, TimeUnit.SECONDS);
                        count++;
                    }
                    if (count >= 3) {
                        System.err.println("客户端已启动，与服务端建立连接失败,30Minutes之后尝试重连!");
                        eventLoop.schedule(() -> start(), 30, TimeUnit.MINUTES);
                        count++;
                    }
                }
            });
            f.channel().closeFuture().sync();

        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {

        new NettyClient(new InetSocketAddress("127.0.0.1", 7066)).start();
    }
}
